﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;

namespace MakeTableTool.Template
{
    public class TemplateCodeGen
    {
        private string fileName;
        private string className;
        private List<TableField> fieldList;
        private ExcelTable excel;
        public TemplateCodeGen(ExcelTable excel)
        {
            this.excel = excel;
            fileName = Path.GetFileNameWithoutExtension(excel.path);
            className = "CSV" + TemplateGenTool.CapitalizeFirstLetter(fileName);
            fieldList = excel.tableFields;
        }

        private const string TEMPLATE = "[Templete]";

        /// <summary>
        /// 生成模板文件
        /// </summary>
        public void GenTemplateFile(string savingPath)
        {
            var templateStr = TemplateGenTool.GetTemplate(TEMPLATE);
            if (string.IsNullOrEmpty(templateStr))
            {
                return;
            }
            Dictionary<string, string> replaceDic = new Dictionary<string, string>();

            replaceDic.Add("className", className);
            replaceDic.Add("sFileName", fileName);
            replaceDic.Add("GetByMuliKey", AnalyzeGetByMuliKey());
            //TODO:缺少多语言
            replaceDic.Add("DefineField", AnalyzeDefineField());
            replaceDic.Add("SetField", AnalyzeSetField());
            replaceDic.Add("SetHashKey", AnalyzeSetHashKey());

            var resultString = TemplateGenTool.ReplaceMulitply(templateStr, replaceDic);

            File.WriteAllText(savingPath,resultString);

            Utils.LogMessage("生产代码文件 {0}", Path.GetFileName(savingPath));
        }

        /// <summary>
        /// 解析替换 %GetByMuliKey%  根据不同的Key生成模板
        /// </summary>
        /// <returns></returns>
        public string AnalyzeGetByMuliKey()
        {
            Dictionary<string, string> map = new Dictionary<string, string>();

            map.Add("className", this.className);
            map.Add("bfileName", TemplateGenTool.CapitalizeFirstLetter(this.fileName));
            for (int i = 1; i <= 5; i++)
            {
                map.Add("t" + i, "");
                map.Add("k" + i, "");
            }
            int keyCount = 0;
            for (int i = 0; i < this.fieldList.Count; i++)
            {
                TableField field = (TableField)this.fieldList[i];
                if (this.fieldList[i].define == TableField.TableDefine.Key)
                {
                    keyCount++;
                    if (keyCount > 5)
                    {
                        throw new Exception("不支持5个以上的Key");
                    }

                    map["t" + keyCount] = field.strFieldType;
                    map["k" + keyCount] = field.Name;
                }
            }
            string type = "[GetByMuliKey(" + keyCount + "key)]";
            string str = TemplateGenTool.GetTemplate(type);
            var returnStr = TemplateGenTool.ReplaceMulitply(str, map);
            return returnStr;
        }


        /// <summary>
        /// 解析字段 %DefineField%
        /// </summary>
        /// <returns></returns>
        public string AnalyzeDefineField()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.fieldList.Count; i++)
            {
                TableField field = (TableField)this.fieldList[i];
                if (field.define != TableField.TableDefine.Delete)
                {
                    Dictionary<string, string> map = new Dictionary<string, string>();
                    map.Add("attrType", field.strFieldType);
                    map.Add("attrName", field.Name);
                    map.Add("destribe", field.Description);

                    string type;
                    //多语言

                    if (!field.isList)
                    {
                        type = "[DefineField]";
                        if (field.define == TableField.TableDefine.BeTranslate)
                        {
                            type = "[DefineFieldTranslate]";
                        }
                    }
                    else
                    {
                        type = "[DefineListField]";
                        if (field.define == TableField.TableDefine.BeTranslate)
                        {
                            type = "[DefineFieldTranslateList]";
                        }
                    }
                    
            
                    
                    
                    string str = TemplateGenTool.GetTemplate(type);
                    String appendStr = TemplateGenTool.ReplaceMulitply(str, map);
                    sb.Append(appendStr);
                }
            }
            return sb.ToString();
        }


        /// <summary>
        /// %SetField% 解析字段
        /// </summary>
        /// <returns></returns>
        public string AnalyzeSetField()
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < this.fieldList.Count; i++)
            {
                TableField field = (TableField) this.fieldList[i];
                {
                    if (field.isBase) //是否为基础类型 (废弃)
                    {
                        if (field.fieldType != TableField.TableBaseType.STRING)
                        {
                            SetFieldBase(field, sb);
                        }
                        else
                        {
                            SetFieldString(field, sb);
                        }
                    }
                    else
                    {
                        //SetCoutomType(field, sb, field.isList);
                    }
                }
            }
            return sb.ToString();
        }


        private void SetFieldBase(TableField field, StringBuilder stringBuffer)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            string type;
            if (!field.isList)
            {
                type = "[SetFieldBase]";
            }
            else
            {
                type = "[SetListBase]";
            }
            map.Add("attrName", field.Name);
            map.Add("toType", field.GetToTypeStr());
            string str = TemplateGenTool.GetTemplate(type);
            var appendStr = TemplateGenTool.ReplaceMulitply(str, map);
            stringBuffer.Append(appendStr);
        }

        private void SetFieldString(TableField field, StringBuilder stringBuffer)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            string type;
            if (!field.isList)
            {

                type = "[SetFieldString]";

                if (field.define == TableField.TableDefine.BeTranslate)
                {
                    type = "[SetTranslation]";
                }
            }
            else
            {
                type = "[SetListString]";

                if (field.define == TableField.TableDefine.BeTranslate)
                {
                    type = "[SetTranslationList]";
                }
            }
            map.Add("attrName", field.Name);

            string str = TemplateGenTool.GetTemplate(type);
            var appendStr = TemplateGenTool.ReplaceMulitply(str, map);
            stringBuffer.Append(appendStr);
        }


        //private void SetCoutomType(TableField field, StringBuffer stringBuffer, Boolean isList)
        //{
        //    Dictionary<string, string> map = new Dictionary<string, string>();
        //    string type;

        //    if (!isList)
        //    {
        //        tagStr = "[SetCoutomType]";
        //    }
        //    else
        //    {
        //        tagStr = "[SetListCoutomType]";
        //    }
        //    map.put("attrName", field.fieldName);
        //    map.put("className", field.fieldType);
        //    map.put("bfileName", Util.GetFileNameUp(field.fieldType));
        //    String str = Util.ReplaceMuli(this.codeTemplate.GetStringByTag(tagStr), map);
        //    stringBuffer.append(str);
        //}



        /// <summary>
        /// 暂时废弃无用 
        /// </summary>
        /// <returns></returns>
        public string AnalyzeSetHashKey()
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            for (int i = 1; i <= 5; i++)
            {
                map.Add("key" + i, "");
            }
            int keyCount = 0;
            for (int i = 0; i < this.fieldList.Count; i++)
            {
                TableField field = (TableField)this.fieldList[i];
                if (((TableField)this.fieldList[i]).define == TableField.TableDefine.Key)
                {
                    keyCount++;
                    if (keyCount > 5)
                    {
                        throw new Exception("不支持大于5个Key");
                    }

                    map["key" + keyCount] = field.Name;
                    //map.Add("key" + keyCount, field.Name);
                }
            }
            string type = "[SetHashKey(" + keyCount + "key)]";

            string str = TemplateGenTool.GetTemplate(type);
            return TemplateGenTool.ReplaceMulitply(str, map);
        }
    }
}
